<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-input
          v-model="query.blurry"
          clearable
          size="small"
          placeholder="输入名称或者邮箱搜索"
          style="width: 200px"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <el-date-picker
          v-model="query.createTime"
          :default-time="['00:00:00', '23:59:59']"
          type="daterange"
          range-separator=":"
          size="small"
          class="date-item"
          value-format="yyyy-MM-dd HH:mm:ss"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
        <el-select
          v-model="query.enabled"
          clearable
          size="small"
          placeholder="状态"
          class="filter-item"
          style="width: 90px"
          @change="crud.toQuery"
        >
          <el-option
            v-for="item in enabledTypeOptions"
            :key="item.key"
            :label="item.display_name"
            :value="item.key"
          />
        </el-select>
        <rrOperation :crud="crud" />
      </div>
      <crudOperation show="" :permission="permission" />
    </div>
    <!--表单渲染-->
    <el-dialog
      append-to-body
      :close-on-click-modal="false"
      :before-close="crud.cancelCU"
      :visible.sync="crud.status.cu > 0"
      :title="crud.status.title"
      width="970px"
    >
      <wang @emits="emits" />
    </el-dialog>
    <!--表格渲染-->
    <el-table
      ref="table"
      v-loading="crud.loading"
      :data="crud.data"
      style="width: 100%"
      @selection-change="crud.selectionChangeHandler"
    >
      <el-table-column :selectable="checkboxT" type="selection" width="55" />
       <el-table-column
        :show-overflow-tooltip="true"
        prop="proName"
        label="项目名称"
      />
       <el-table-column
        :show-overflow-tooltip="true"
        prop="proWebUrl"
        label="外网链接"
      />
      <el-table-column
        :show-overflow-tooltip="true"
        prop="proJishu"
        label="技术栈"
      />
        <el-table-column
        :show-overflow-tooltip="true"
        prop="proNandu"
        label="项目难度"
      />
       <el-table-column
        :show-overflow-tooltip="true"
        prop="proTuanduiNum"
        label="团队人数"
      />
        <el-table-column
        :show-overflow-tooltip="true"
        prop="zanNum"
        label="点赞数"
      />
      <el-table-column
        :show-overflow-tooltip="true"
        prop="readNum"
        label="浏览数"
      />
        <el-table-column
        :show-overflow-tooltip="true"
        prop="pingjiaNum"
        label="评价数"
      />
      <el-table-column
        :show-overflow-tooltip="true"
        prop="isTop"
        label="是否置顶"
      />
      <!--<el-table-column v-if="columns.visible('dept')" :show-overflow-tooltip="true" width="110" prop="dept" label="部门 / 岗位">
            <template slot-scope="scope">
              <div>{{ scope.row.dept.name }} / {{ scope.row.job.name }}</div>
            </template>
          </el-table-column>-->
      <el-table-column
        :show-overflow-tooltip="true"
        prop="isEnabled"
        label="是否启用"
      />
      <el-table-column
        :show-overflow-tooltip="true"
        prop="createTime"
        label="创建时间"
      />
      <el-table-column
        :show-overflow-tooltip="true"
        prop="userNickName"
        label="项目创建人"
      />
      <el-table-column
        v-permission="['admin', 'user:edit', 'user:del']"
        label="操作"
        width="125"
        align="center"
        fixed="right"
      >
        <template slot-scope="scope">
          <udOperation :data="scope.row" :permission="permission" />
        </template>
      </el-table-column>
    </el-table>
    <!--分页组件-->
    <pagination />
  </div>
</template>

<script>
import crudUser from "@/api/system/user";
import { isvalidPhone } from "@/utils/validate";
import { getAll, getLevel } from "@/api/system/role";
import { getAllJob } from "@/api/system/job";
import CRUD, { presenter, header, form, crud } from "@crud/crud";
import rrOperation from "@crud/RR.operation";
import crudOperation from "@crud/CRUD.operation";
import udOperation from "@crud/UD.operation";
import pagination from "@crud/Pagination";
import Treeselect from "@riophae/vue-treeselect";
import { mapGetters } from "vuex";
import wang from "./wangeditor";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

let userRoles = [];
// crud交由presenter持有
const defaultCrud = CRUD({
  title: "用户",
  url: "api/sysUser",
  crudMethod: { ...crudUser },
});
const defaultForm = {
  username: null,
  nickName: null,
  sex: "男",
  email: null,
  enabled: "false",
  roles: [],
  job: { id: null },
  dept: { id: null },
  phone: null,
  crud: crud,
};
export default {
  name: "User",
  components: {
    Treeselect,
    crudOperation,
    rrOperation,
    udOperation,
    pagination,
    wang,
  },
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
  // 数据字典
  dicts: ["user_status"],
  data() {
    // 自定义验证
    const validPhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入电话号码"));
      } else if (!isvalidPhone(value)) {
        callback(new Error("请输入正确的11位手机号码"));
      } else {
        callback();
      }
    };
    return {
      height: document.documentElement.clientHeight - 180 + "px;",
      deptName: "",
      depts: [],
      deptDatas: [],
      jobs: [],
      level: 3,
      roles: [],
      defaultProps: { children: "children", label: "name" },
      permission: {
        add: ["admin", "user:add"],
        edit: ["admin", "user:edit"],
        del: ["admin", "user:del"],
      },
      enabledTypeOptions: [
        { key: "true", display_name: "激活" },
        { key: "false", display_name: "锁定" },
      ],
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 2,
            max: 20,
            message: "长度在 2 到 20 个字符",
            trigger: "blur",
          },
        ],
        nickName: [
          { required: true, message: "请输入用户昵称", trigger: "blur" },
          {
            min: 2,
            max: 20,
            message: "长度在 2 到 20 个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱地址", trigger: "blur" },
          { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" },
        ],
        roles: [{ required: true, message: "请选择角色", trigger: "blur" }],
        phone: [{ required: true, trigger: "blur", validator: validPhone }],
      },
    };
  },
  computed: {
    ...mapGetters(["user"]),
  },
  created() {
    this.$nextTick(() => {
      this.crud.toQuery();
      this.crud.msg.add = "新增成功，默认密码：123456";
    });
  },
  mounted: function () {
    const that = this;
    window.onresize = function temp() {
      that.height = document.documentElement.clientHeight - 180 + "px;";
    };
  },
  methods: {
    emits(item) {
      console.log(item.key);
      if (!item.key) {
        this.crud.submitCU();
      } else {
        this.crud.cancelCU();
      }
    },
    changeRole(value) {
      userRoles = [];
      value.forEach(function (data, index) {
        const role = { id: data };
        userRoles.push(role);
      });
    },
    [CRUD.HOOK.afterAddError](crud) {
      this.afterErrorMethod(crud);
    },
    [CRUD.HOOK.afterEditError](crud) {
      this.afterErrorMethod(crud);
    },
    afterErrorMethod(crud) {
      // 恢复select
      const initRoles = [];
      userRoles.forEach(function (role, index) {
        initRoles.push(role.id);
      });
      crud.form.roles = initRoles;
    },
    deleteTag(value) {
      userRoles.forEach(function (data, index) {
        if (data.id === value) {
          userRoles.splice(index, value);
        }
      });
    },
    beforeInit() {
      this.url = "api/users";
      return true;
    },
    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
      this.getDepts();
      this.getRoles();
      this.getRoleLevel();
      form.enabled = form.enabled.toString();
    },
    // 打开编辑弹窗前做的操作
    [CRUD.HOOK.beforeToEdit](crud, form) {
      userRoles = [];
      const roles = [];
      form.roles.forEach(function (role, index) {
        roles.push(role.id);
        // 初始化编辑时候的角色
        const rol = { id: role.id };
        userRoles.push(rol);
      });
      form.roles = roles;
    },
    // 提交前做的操作
    [CRUD.HOOK.afterValidateCU](crud) {
      if (this.roles.length === 0) {
        this.$message({
          message: "角色不能为空",
          type: "warning",
        });
        return false;
      }
      crud.form.roles = userRoles;
      return true;
    },
    // // 获取左侧部门数据
    // getDeptDatas() {
    //   const sort = 'id,desc'
    //   const params = { sort: sort }
    //   if (this.deptName) { params['name'] = this.deptName }
    //   getDepts(params).then(res => {
    //     this.deptDatas = res.content
    //   })
    // },
    // // 获取弹窗内部门数据
    // getDepts() {
    //   getDepts({ enabled: true }).then(res => {
    //     this.depts = res.content
    //   })
    // },
    // // 切换部门
    // handleNodeClick(data) {
    //   if (data.pid === 0) {
    //     this.query.deptId = null
    //   } else {
    //     this.query.deptId = data.id
    //   }
    //   this.crud.toQuery()
    // },
    // 改变状态
    changeEnabled(data, val) {
      this.$confirm(
        '此操作将 "' +
          this.dict.label.user_status[val] +
          '" ' +
          data.username +
          ", 是否继续？",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          crudUser
            .edit(data)
            .then((res) => {
              this.crud.notify(
                this.dict.label.user_status[val] + "成功",
                CRUD.NOTIFICATION_TYPE.SUCCESS
              );
            })
            .catch(() => {
              data.enabled = !data.enabled;
            });
        })
        .catch(() => {
          data.enabled = !data.enabled;
        });
    },
    // 获取弹窗内角色数据
    getRoles() {
      getAll()
        .then((res) => {
          this.roles = res;
        })
        .catch(() => {});
    },
    // // 获取弹窗内岗位数据
    // getJobs(id) {
    //   getAllJob(id).then(res => {
    //     this.jobs = res.content
    //   }).catch(() => { })
    // },
    // // 点击部门搜索对应的岗位
    // selectFun(node, instanceId) {
    //   this.getJobs(node.id)
    //   this.form.job.id = null
    // },
    // 获取权限级别
    getRoleLevel() {
      getLevel()
        .then((res) => {
          this.level = res.level;
        })
        .catch(() => {});
    },
    checkboxT(row, rowIndex) {
      return row.id !== this.user.id;
    },
  },
};
</script>

<style scoped>
</style>
